package com.liu.stockmarket.repository.database

import android.content.Context
import android.util.Log
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.TypeConverters
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import com.liu.stockmarket.repository.database.converter.Converters
import com.liu.stockmarket.repository.database.dao.ProfitDao
import com.liu.stockmarket.repository.database.dao.StockDao
import com.liu.stockmarket.repository.database.dao.TransactionRecordDao
import com.liu.stockmarket.repository.database.entity.ProfitEntity
import com.liu.stockmarket.repository.database.entity.StockEntity
import com.liu.stockmarket.repository.database.entity.TransactionRecordEntity
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch

@Database(
    entities = [StockEntity::class, TransactionRecordEntity::class, ProfitEntity::class],
    version = 1,
    exportSchema = false
)
@TypeConverters(value = [Converters::class])
abstract class MyRoomDataBase : RoomDatabase() {


    abstract fun stockDao(): StockDao
    abstract fun transactionRecordDao(): TransactionRecordDao
    abstract fun profitDao(): ProfitDao


    companion object {
        @Volatile
        private var INSTANCE: MyRoomDataBase? = null


        private val MIGRATION_1_2 = object : Migration(1, 2) {
            override fun migrate(database: SupportSQLiteDatabase) {
                database.execSQL(
                    "create table 'stage' ('id' INTEGER,'name' TEXT not null," +
                            "'account_id' INTEGER not null,start_date TEXT not null,primary key('id'))"
                )
            }

        }
        private val MIGRATION_2_3 = object : Migration(2, 3) {
            override fun migrate(database: SupportSQLiteDatabase) {
                database.execSQL(
                    "ALTER TABLE stage ADD COLUMN pub_year INTEGER"
                )
            }

        }

        // 数据库版本升级策略
        private val ALL_MIGRATIONS = arrayOf(
            MIGRATION_1_2, MIGRATION_2_3
        )

        fun getDatabase(
            context: Context,
            scope: CoroutineScope
        ): MyRoomDataBase {
            // if the INSTANCE is not null, then return it,
            // if it is, then create the database
            return INSTANCE ?: synchronized(this) {
                val instance = Room.databaseBuilder(
                    context.applicationContext,
                    MyRoomDataBase::class.java,
                    "word_database"
                )
                    // Wipes and rebuilds instead of migrating if no Migration object.
                    // Migration is not part of this codelab.
//                    .addMigrations(*ALL_MIGRATIONS)
                    .fallbackToDestructiveMigration()
                    .addCallback(WordDatabaseCallback(scope))
                    .build()
                INSTANCE = instance
                // return instance
                instance
            }
        }

        private class WordDatabaseCallback(
            private val scope: CoroutineScope
        ) : RoomDatabase.Callback() {
            /**
             * Override the onCreate method to populate the database.
             */
            override fun onCreate(db: SupportSQLiteDatabase) {
                super.onCreate(db)
                // If you want to keep the data through app restarts,
                // comment out the following line.
                INSTANCE?.let { database ->
                    scope.launch {
                        Log.i("MyRoomDataBase", "初始化数据库")
                    }
                }
            }
        }

    }
}